<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This file keeps track of upgrades to the email_list block
 *
 * Sometimes, changes between versions involve alterations to database structures
 * and other major things that may break installations.
 *
 * The upgrade function in this file will attempt to perform all the necessary
 * actions to upgrade your older installation to the current version.
 *
 * If there's something it cannot do itself, it will tell you what you need to do.
 *
 * The commands in here will all be database-neutral, using the methods of
 * database_manager class
 *
 * Please do not forget to use upgrade_set_timeout()
 * before any action that may take longer time to finish.
 *
 * @package   blocks-email_list
 * @copyright 2006 by <toni.mas at uib dot es>.
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since     2.0
 */

/**
 * Upgrade function
 *
 * @param int $oldversion The version we are upgrading from
 * @return void
 */

function xmldb_block_email_list_upgrade($oldversion=0) {
    global $CFG, $DB;

    $dbman = $DB->get_manager();


    if ($oldversion < 2007062205) {
        $fields = array(
                        'mod/email:viewmail',
                        'mod/email:addmail',
                        'mod/email:reply',
                        'mod/email:replyall',
                        'mod/email:forward',
                        'mod/email:addsubfolder',
                        'mod/email:updatesubfolder',
                        'mod/email:removesubfolder'    );

        /// Remove no more used fields
        $table = new xmldb_table('capabilities');

        foreach ($fields as $name) {
            $field = new xmldb_field($name);
            $dbman->drop_field($table, $field);
        }

        if ($email_list = $DB->get_record('block', array('name' => 'email_list'))) {
             $email_list->cron = 1;
             $DB->update_record('block', $email_list);
        }

        upgrade_block_savepoint(true, 2007062205, 'email_list');
    }

    if ($oldversion < 2007072003) {
        // Add marriedfolder2courses flag on email_preferences
        $table = new xmldb_table('email_preference');

        $field = new xmldb_field('marriedfolders2courses');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

        $dbman->add_field($table, $field);


        // Add course ID on email_folder
        $table = new xmldb_table('email_folder');

        $field = new xmldb_field('course');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

        $dbman->add_field($table, $field);

        // Add index
        $key = new xmldb_key('course');
        $key->set_attributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));

        $dbman->add_key($table, $key);

        /// Block savepoint reached
        upgrade_block_savepoint(true, 2007072003, 'email_list');

    }

    if ($oldversion < 2008061400 ) {

        // Add reply and forwarded info field on email_mail.
        $table = new xmldb_table('email_send');

        $field = new xmldb_field('answered');
        $field->set_attributes(XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

        $dbman->add_field($table, $field);

        /// Block savepoint reached
        upgrade_block_savepoint(true, 2008061400, 'email_list');
    }

    // Solve old problems
    if ($oldversion < 2008061600 ) {
        $table = new xmldb_table('email_preference');
        $field = new xmldb_field('marriedfolders2courses');

        if (! $dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

            $dbman->add_field($table, $field);
        }

        $table = new xmldb_table('email_folder');

        $field = new xmldb_field('course');

        if (! $dbman->field_exists($table, $field) ) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

            $dbman->add_field($table, $field);

            // Add index
            $key = new xmldb_key('course');
            $key->set_attributes(XMLDB_KEY_FOREIGN, array('course'), 'course', array('id'));

            $dbman->add_key($table, $key);
        }

        /// Block savepoint reached
        upgrade_block_savepoint(true, 2008061600, 'email_list');

    }

    // Add new index
    if ($oldversion < 2008081602) {
        // Add combine key on foldermail
        $table = new xmldb_table('email_foldermail');
        $index = new xmldb_index('folderid-mailid');
        $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('folderid', 'mailid'));

        if (! $dbman->index_exists($table, $index)) {
            /// Launch add index
            $dbman->add_index($table, $index);
        }

        /// Block savepoint reached
        upgrade_block_savepoint(true, 2008081602, 'email_list');

    }

    // Upgrading to Moodle 2.0
    if ( $oldversion < 2009040200 ) {

        // Portable SQL staments to Oracle, MySQL and PostgreSQL NOT APPLYCABLE to MSSQL
        if ($CFG->dbname != 'mssql') {
            // Filter
            $dbman->execute_sql('ALTER TABLE {email_filter} RENAME TO {block_email_list_filter}');

            // Folder
            $dbman->execute_sql('ALTER TABLE {email_folder} RENAME TO {block_email_list_folder}');

            // Foldermail
            $dbman->execute_sql('ALTER TABLE {email_foldermail} RENAME TO {block_email_list_foldermail}');

            // Mail
            $dbman->execute_sql('ALTER TABLE {email_mail} RENAME TO {block_email_list_mail}');

            // Preference
            $dbman->execute_sql('ALTER TABLE {email_preference} RENAME TO {block_email_list_preference}');

            // Send
            $dbman->execute_sql('ALTER TABLE {email_send} RENAME TO {block_email_list_send}');

            // Subfolder
            $dbman->execute_sql('ALTER TABLE {email_subfolder} RENAME TO {block_email_list_subfolder}');
        }

        // Change module name to Standard eMail name.
        if ( $logs = $DB->get_records('log_display', array('module' => 'email'))) {

            foreach ($logs as $log) {
                $DB->set_field('log_display', 'module', 'block_email_list', array('id', $log->id));
            }
        }

        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2009040200, 'email_list');
    }

    // Add field respondedid into block_email_list_mail table because, if one mail has replied, know this parent.
    if ( $oldversion < 2010021401 ) {
        $table = new xmldb_table('block_email_list_mail');
        $field = new xmldb_field('respondedid');

        if (! $dbman->field_exists($table, $field) ) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', null);

            $dbman->add_field($table, $field);
        }

        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2010021400, 'email_list');
    }

    // SBCCMCP-29: user settings for email refresh-rate
    if ($oldversion < 2010101501) {
        $table = new xmldb_table('block_email_list_preference');
        $field = new xmldb_field('emailrefreshrate');

        if (! $dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED,
                                   XMLDB_NOTNULL, null, '600', 'marriedfolders2courses');
            $dbman->add_field($table, $field);
        }

        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2010101501, 'email_list');
    }

    // SBCCMCP-36: mail lists for users
    // Requires: changes to block_email_list_send and
    // two new tables required to support mail lists:
    // block_email_list_lists and block_email_list_members
    // BJB101022: remove all enums, since not portable across RDBMs
    if ( $oldversion < 2010102204 ) {

        $tabname = 'block_email_list_send';
        $table = new xmldb_table($tabname);
        $field = new xmldb_field('type');

        // save field values
        $records = $DB->get_records($tabname, array(), '', 'id, type');
        // drop field
        $dbman->drop_field($table, $field);
        // re-add w/o enum
        $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL,
                   null, 'to', 'mailid');
        $dbman->add_field($table, $field);

        // Copy old field data to new field
        foreach ($records as $rec) {

            if (!($DB->update_record($tabname, $rec))) {
                break;
            }
        }

        $tabname = 'block_email_list_folder';
        $table = new xmldb_table('block_email_list_folder');
        $field = new xmldb_field('isparenttype');

        // save field values
        $records = $DB->get_records($tabname, array(), '', 'id, isparenttype');
        // drop field
        $dbman->drop_field($table, $field);
        // re-add w/o enum
        $field->set_attributes(XMLDB_TYPE_CHAR, '20', null, null,
                   null, null, 'timecreated');
        $dbman->add_field($table, $field);

        // Copy old field data to new field
        foreach ($records as $rec) {

            if (!($DB->update_record($tabname, $rec))) {
                break;
            }
        }

        // create new tables for mailing lists
        $file = new XMLDBFile($CFG->dirroot .'/blocks/email_list/db/install.xml');
        $file->loadXMLStructure();

        foreach ($file->xmldb_structure->tables as $tbl) {

            if ($tbl->name == 'block_email_list_lists') {

                if (! $dbman->create_table($tbl)) {
                    return false;
                }
            }

            if ($tbl->name == 'block_email_list_members') {

                if (! $dbman->create_table($tbl)) {
                    return false;
                }
            }
        }

        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2010102204, 'email_list');
    }

    // SBCCMCP-36: mailing lists
    if ($oldversion < 2010102601) {
        // drop listid from block_email_list_send
        $tabname = 'block_email_list_send';
        $table = new xmldb_table($tabname);
        $field = new xmldb_field('listid');

        if ($dbman->field_exists($table, $field) ) {
            $dbman->drop_field($table, $field);
        }

        // rename field listid to id in block_email_list_lists
        $tabname = 'block_email_list_lists';
        $table = new xmldb_table($tabname);
        $field = new xmldb_field('listid');
        $field->set_attributes(XMLDB_TYPE_INTEGER, 10, XMLDB_UNSIGNED,
                              XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null);

        if ($dbman->field_exists($table, $field)) {
            $dbman->rename_field($table, $field, 'id');
        }

        // Only compatible with 2.0 or newer versions

        /// Block savepoint reached
        upgrade_block_savepoint(true, 2010102601, 'email_list');
    }

    // SBCCMCP-28: new field 'toext' in block_email_list_send
    if ($oldversion < 2010102700) {
        $table = new xmldb_table('block_email_list_send');
        $field = new xmldb_field('toext');

        if (! $dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_TEXT, 'small', null, null,
                                   null, null, 'answered');
            $dbman->add_field($table, $field);
        }

        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2010102700, 'email_list');
    }

    if ($oldversion < 2011020100) {
        $table = new xmldb_table('block_email_list_lists');
        $field = new xmldb_field('listname');
        if ($dbman->field_exists($table, $field)) {
            $field->set_attributes(XMLDB_TYPE_CHAR, 255, null,
                                   null, null, null, '');
            $dbman->change_field_type($table, $field);
        }
        // Only compatible with 2.0 or newer versions
        /// Block savepoint reached
        upgrade_block_savepoint(true, 2011020100, 'email_list');
    }

    if ($oldversion < 2012020800) {
        $sql = "ALTER TABLE  {$CFG->prefix}block_email_list_mail ADD INDEX {$CFG->prefix}blocemailistmail_ci_ix (course,id)";
        $DB->execute($sql);
    }

    if ($oldversion < 2012030600) {
        $sql = "DELETE FROM {$CFG->prefix}block_instances WHERE blockname='email_list' && pagetypepattern = 'site-index'";
        $DB->execute($sql);
    }

    if ($oldversion < 2012032900) {
        set_config('email_enable_ajax', 0);
    }

    return true;
}
